
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTD = 'REJECTD'
class Promise {
    constructor (executor) {
        this.status = PENDING //默认状态为进行中
        this.value = undefined //成功的值
        this.reason = undefined//失败的值
        // 解决异步问题
        this.onFulfilledCallbacks = [] //存放成功的回调函数
        this.onRejectedCallbacks = [] //存放失败的回调函数
        // 成功的回调
        const resolve = value =>{
            if (this.status === PENDING) {
                this.value = value
                this.status = FULFILLED
                this.onFulfilledCallbacks.forEach(fn=>fn())
            }
        }
        // 失败的回调
        const reject = reason => {
            if (this.status === PENDING) {
                this.reason = reason
                this.status = REJECTD
                this.onRejectedCallbacks.forEach(fn=>fn())
            }
        }
        // try 捕获异常
        try {
            // 立即执行  把rersolve和reject传入
            executor(resolve, reject)
        } catch(error) {
            reject(error)
        }

    }
    // then函数
    then = (onFulfilled, onRejected) => {
        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        }
        if (this.status === REJECTD) {
            onRejected(this.reason)
        }
        if (this.status === PENDING) {
            this.onFulfilledCallbacks.push(() => { onFulfilled(this.value) })
            this.onRejectedCallbacks.push(()=>{onRejected(this.reason)})
        }
    }

    // catch
    catch = onRejected => {
        if (this.status === REJECTD) {
            onRejected(this.reason)
        }
    }
}
function promise (url) {
    return  new Promise((resolve, reject) => {
        if (url === 'http') setTimeout(() => { resolve('请求成功') }, 1000)
        setTimeout(()=>{reject('请求失败')}, 2000)
    })
}

promise('htt1').then(res => {
    console.log(res)
}, err => {
    // 收集依赖 -> 触发通知 -> 取出依赖执行
    console.log(err)
})

